package dryworks.jsf.parsers;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import dryworks.examples.create.model.CreateExampleTask;
import dryworks.jsf.examples.generator.SiteGenerator;
import dryworks.jsf.examples.generator.SiteGeneratorRunner;

public class JSPParser {
	String jspFileURI;

	String source;

	public String getJspFileURI() {
		return jspFileURI;
	}

	public void setJspFileURI(String jspFileURI) {
		this.jspFileURI = jspFileURI;
	}

	public void visitAllNodes(INodeVisitor nodeVisitor) throws ParserConfigurationException, SAXException, IOException {
		Document doc = parserXML(new FileInputStream(getJspFileURI()));
		visit(doc, nodeVisitor);
	}

	private void visit(Node node, INodeVisitor nodeVisitor) {
		nodeVisitor.visit(node);
		NodeList nl = node.getChildNodes();
		for (int i = 0, cnt = nl.getLength(); i < cnt; i++) {
			//System.out.println("[" + nl.item(i) + "]");
			
			visit(nl.item(i), nodeVisitor);
		}
	}

	public Document parserXML(InputStream stream)
			throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		DocumentBuilder db;
		dbf.setValidating(false);
		db = dbf.newDocumentBuilder();

		Document document = db.parse(stream);
		return document;
	}
	public static void main(String[] args) {
		try {
			
			File projectFolder = new File(SiteGeneratorRunner.calculateCurrentWorkspaceDir(),
					"TestICEFaces");
			File t = new File("TestICEFaces/WebContent/examplesExplorer.jspx");
			if (t.exists()) {
				System.err.println("no file!");
			}
			JSPParser parser = new JSPParser();
			parser.setJspFileURI("WebContent/examplesExplorer.jspx");
//			parser.visitAllNodes(new INodeVisitor() {
//
//				@Override
//				public void visit(Node node) {
//					System.out.println(""+node.getNodeName());
//					
//				}});
			NodesNamesCollector collector = new NodesNamesCollector();
			parser.visitAllNodes(collector);
			System.out.println(collector.getNames());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
